<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\services\order;

use app\kefuapi\controller\Order;
use app\model\order\StoreOrder;
use app\model\user\UserAddress;
use app\services\BaseServices;
use crmeb\exceptions\ApiException;
use think\facade\Db;

class OrderAddressService extends BaseServices
{
    private $userAddressModel;

    public function __construct()
    {
        $this->userAddressModel = new UserAddress();
    }

    /**
     * @param $params
     * @return array
     * 订单地址列表
     */
    public function index($params)
    {
        $listParams = [
            'where' => [
                ['uid', '=', $params['user_id']],
                ['is_del', '=', 0],
            ]
        ];
        $listParams['fields'] = ['id', 'uid', 'detail', 'is_default', 'real_name', 'province', 'city', 'city_id', 'district','phone'];
        $listParams['order'] = [['field' => 'is_default', 'type' => 'desc']];

        $result = $this->getModelList(UserAddress::where('1=1'), $listParams);
        foreach ($result['list'] as $key => $val) {
            $result['list'][$key]['is_default_name'] = UserAddress::IS_DEFAULT_NAME[$val['is_default']];
        }

        return $result;
    }

    /**
     * @param $params
     * @return void
     * 订单地址添加
     */
    public function add($params)
    {
        Db::transaction(function () use ($params) {
            //如果是默认，则把此用户下所有地址置为非默认
            if($params['is_default'] == 1) {
                UserAddress::where('uid', $params['uid'])->update(['is_default' => 0]);
            }


            $count = UserAddress::where('uid', $params['uid'])->where('is_del', 0)->count();
            if ($count == 0) {
                $params['is_default'] = 1;
            }

            $params = $this->dbColumnFormat($this->userAddressModel->getTable(), $params);
            $id = UserAddress::insertGetId($params);
            if(!$id) {
                throw new ApiException(100005);
            }
        });
    }

    /**
     * @param $params
     * @return array|string[]
     * 订单地址详情
     */
    public function view($params)
    {
        $result = $this->viewById($this->userAddressModel, $params['address_id'], ['real_name', 'phone', 'district', 'detail', 'post_code', 'email', 'is_default', 'province', 'city', 'city_id', 'district']);

        return $result;
    }

    /**
     * @param $params
     * @return void
     * 订单地址编辑
     */
    public function edit($params)
    {
        Db::transaction(function () use ($params) {

            $order_id = $params['order_id'] ?? 0;

            $params = $this->dbColumnFormat($this->userAddressModel->getTable(), $params);

            //如果编辑为默认地址，则先把当前用户下所有地址置为非默认
            if(isset($params['is_default']) && $params['is_default'] == 1) {
                UserAddress::where('uid', $params['uid'])->update(['is_default' => 0]);
            }
            if ($order_id) {

                $order = StoreOrder::where('is_del', 0)->where('uid', $params['uid'])->where('id', $order_id)->whereIn('status', [0, 1])->find();
                if (!$order) {
                    throw new ApiException(400118);
                }


                $order->update([
                    'id'    =>  $order_id,
                    'real_name' =>  $params['real_name'],
                    'user_phone'    =>  $params['phone'],
                    'user_address'  =>  $params['province'] . ' ' . $params['city'] . ' ' . $params['district'] . ' ' . $params['detail'],
                    'province'  =>  $params['province'],
                    'city'  =>  $params['city'],
                    'district'  =>  $params['district'],
                    'city_id'   =>  $params['city_id']
                ]);
            }

            UserAddress::update($params);
        });
    }

    /**
     * @param $params
     * @return void
     * 订单地址删除
     */
    public function delete($params)
    {
        Db::transaction(function () use ($params) {
            UserAddress::destroy($params['address_id']);
        });
    }
}